/*
 * @Author: EternityJun 2438965023@qq.com
 * @Date: 2025-05-08 16:36:32
 * @LastEditors: EternityJun 2438965023@qq.com
 * @LastEditTime: 2025-05-17 16:51:47
 * @FilePath: \private-domain-small-program\src\store\user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { loginApi, LoginData } from '@/service/app'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useAccessStore } from './access'

const initState = { nickname: '', avatar: '' }

export const useUserStore = defineStore(
  'user',
  () => {
    const accessStore = useAccessStore()

    const userInfo = ref<IUserInfo>({ ...initState })

    const setUserInfo = (val: IUserInfo) => {
      userInfo.value = val
    }

    const clearUserInfo = () => {
      userInfo.value = { ...initState }
    }
    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...initState }
    }

    const login = async (loginForm: LoginData) => {
      try {
        const { code, data } = await loginApi({ data: loginForm })

        if (code === 200) {
          accessStore.setAccessToken(data.token)
          uni.switchTab({
            url: '/pages/home/index',
          })
        }
      } catch (error) {
        accessStore.removeAccessToken()
        throw error
      }
    }
    return {
      userInfo,
      setUserInfo,
      clearUserInfo,
      reset,
      login,
    }
  },
  {
    persist: true,
  },
)
